package service;

import dao.ShopDao;
import dao.StoreDao;
import po.*;

public class BuyerService {

	public static boolean choose(String productId, String buyerId, String sellerId, int amount) { // 加入购物车
		if (amount <= 0) return false;
		
		Shop s = new Shop();
		s.setProductId(productId);
		s.setBuyerId(buyerId);
		s.setSellerId(sellerId);
		s.setAmount(amount);
		// 设置状态
		s.setStatus(0); // 0为单纯加入购物车的商品 1为已下单 2为成功交易
		// store 商店的库存 减少
		Store st = new Store();
		st.setProductId(productId);
		st.setSellerId(sellerId);
		StoreDao.queryOneRecord(st);
		if (st.getAmount() < amount)
			return false;
		ShopDao.addOneRecord(s);
		st.setAmount(st.getAmount() - amount);
		StoreDao.updataOneRecord(st);
		return true;
	}
	
	public static boolean placeOrder(String productId, String buyerId, String sellerId) { // 下单
		Shop s = new Shop();
		s.setProductId(productId);
		s.setBuyerId(buyerId);
		s.setSellerId(sellerId);
		ShopDao.queryOneRecord(s);
		// 设置状态
		s.setStatus(1); // 0为单纯加入购物车的商品 1为已下单 2为成功交易
		ShopDao.updataOneRecord(s);
		
		return true;
	}
	
	public static Shop[] getShoppingCart(String buyerId) {
		Shop[] allShop = ShopDao.queryAllRecord();
		Shop[] myShop;
		int amount=0;
		for (Shop temp: allShop) {
			if (temp.getBuyerId().equals(buyerId) && temp.getStatus() == 0)
				amount++;
		}
		myShop = new Shop[amount];
		amount=0;
		for (Shop temp: allShop) {
			if (temp.getBuyerId().equals(buyerId) && temp.getStatus() == 0) {
				myShop[amount++] = temp;
			}
		}
		return myShop;
	}
	
	public static Shop[] getAllOK(String buyerId) {
		Shop[] allShop = ShopDao.queryAllRecord();
		Shop[] myOrder;
		int amount=0;
		for (Shop temp: allShop) {
			if (temp.getBuyerId().equals(buyerId) && temp.getStatus() == 2)
				amount++;
		}
		myOrder = new Shop[amount];
		amount=0;
		for (Shop temp: allShop) {
			if (temp.getBuyerId().equals(buyerId) && temp.getStatus() == 2)
				myOrder[amount++] = temp;
		}
		return myOrder;
	}
	
	public static Store[] getAllStore() {
		return StoreDao.queryAllRecord();
	}
	
}
